﻿'use strict';

exports.main = async (event, context) => {
  console.log('=== testInteractionMessages 云函数开始 ===')
  console.log('1. 接收参数:', event)
  
  const db = uniCloud.database();
  const { action, userId } = event;

  try {
    if (action === 'check') {
      // 检查数据库表状态
      console.log('2. 检查数据库表状态...')
      
      // 检查 interaction-messages 表是否存在数据
      const countResult = await db.collection('interaction-messages').count();
      console.log('3. interaction-messages 表记录数:', countResult.total)
      
      // 检查用户相关的消息
      if (userId) {
        const userMessages = await db.collection('interaction-messages')
          .where({
            target_user_id: userId
          })
          .get();
        console.log('4. 用户相关消息数:', userMessages.data.length)
        console.log('5. 用户消息详情:', userMessages.data)
      }
      
      return {
        code: 200,
        msg: '检查完成',
        data: {
          totalCount: countResult.total,
          userMessages: userId ? await db.collection('interaction-messages').where({target_user_id: userId}).get() : null
        }
      };
    } else if (action === 'insert') {
      // 插入测试数据
      console.log('2. 插入测试数据...')
      
      const testData = {
        type: 'like',
        target_user_id: userId || '68bf91621c90b6a2f184462a',
        sender_user_id: 'test_sender_id',
        sender_nickname: '测试用户',
        sender_avatar: '/static/images/default-avatar.png',
        post_id: 'test_post_id',
        post_title: '测试帖子',
        content: '对您的帖子进行了点赞',
        create_time: new Date(),
        is_read: false,
        status: 'active'
      };
      
      console.log('3. 测试数据:', testData)
      
      const result = await db.collection('interaction-messages').add(testData);
      console.log('4. 插入结果:', result)
      
      return {
        code: 200,
        msg: '测试数据插入成功',
        data: result
      };
    } else {
      return {
        code: 400,
        msg: '请指定 action: check 或 insert'
      };
    }
  } catch (error) {
    console.error(' 测试失败:', error);
    return {
      code: 500,
      msg: '测试失败',
      error: error.message
    };
  }
};
